﻿<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="basePath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>属性管理</title>
    <jsp:include page="/resources/inc/head.jsp" />
    <link href="${basePath}/resources/zheng-admin/plugins/zTree_v3/css/metroStyle/metroStyle.css" rel="stylesheet"/>
    <link href="${basePath}/resources/zheng-admin/plugins/bootstrap_switch/css/bootstrap3/bootstrap-switch.css"
          rel="stylesheet"/>
</head>
<body>
<aside id="iframe_aside" class="sidebar1">
    <div class="zTreeDemoBackground left">
        <ul id="aside_tree" class="ztree"></ul>
    </div>
</aside>
<div id="main">
    <div id="toolbar">
        <shiro:hasPermission name="product:attribute:create">
            <a class="waves-effect waves-button" href="javascript:;"
               onclick="doAdd()">
                <i class="zmdi zmdi-plus"></i>新增商品属性
            </a>
        </shiro:hasPermission>
        <shiro:hasPermission name="product:attribute:delete">
            <a class="waves-effect waves-button" href="javascript:;"
               onclick="batchDelete('${basePath}/manage/product/attribute/delete')">
                <i class="zmdi zmdi-close"></i>删除商品属性</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="product:attribute:update">
            <a class="waves-effect waves-button" href="javascript:;"
               onclick="copy()">
                <i class="zmdi zmdi-copy"></i>复制商品属性</a>
        </shiro:hasPermission>
    </div>
    <table id="table"></table>
</div>
<jsp:include page="/resources/inc/footer.jsp" />
<script src="${basePath}/resources/zheng-admin/plugins/bootstrap_switch/js/bootstrap-switch.js"></script>
<script>
    function doAdd() {
        var treeObj = $.fn.zTree.getZTreeObj("aside_tree");
        var nodes = treeObj.getSelectedNodes();
        if (nodes < 1) {
            layer.msg('请选择一项分类！', {icon: 5});
            return;
        }
        if (nodes[0].id == 0) {
            layer.msg('无法为顶级添加属性！', {icon: 5});
            return;
        }
        var param = "productCategoryId=" + nodes[0].id;
        openPage('新增属性', '${basePath}/manage/product/attribute/create', null, param);
    }
    function copy() {
        var url = '${basePath}/manage/product/attribute/copy';
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length < 1) {
            layer.msg('至少选择一项属性！', {icon: 5});
            return;
        }
        var keyIds = [];
        for (var i = 0; i < rows.length; i++) {
            keyIds.push(rows[i].id);
        }
        openPage('复制属性', url, null, "keyIds=" + JSON.stringify(keyIds));
    }
    var query = {};
    var $table = $('#table');
    $(function () {
        // bootstrap table初始化
        $table.bootstrapTable({
            url: '${basePath}/manage/product/attribute/list',
            height: getHeight(),
            striped: true,//隔行变色
            showRefresh: true,
            showColumns: true,//是否显示 内容列下拉框
            minimumCountColumns: 2,//当列数小于此值时，将隐藏内容列下拉框
            clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
            pagination: false,//设置为 true 会在表格底部显示分页条
            paginationLoop: false,//设置为 true 启用分页条无限循环的功能。
            sidePagination: 'server',
            silentSort: false,//设置为 false 将在点击分页按钮时，自动记住排序项。仅在 sidePagination设置为 server时生效.
            smartDisplay: false,//True to display pagination or card view smartly.
            escape: true,//转义HTML字符串，替换 &, <, >, ", `, 和 ' 字符.
            searchOnEnterKey: true,//设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
            idField: 'id',//指定主键列
            maintainSelected: true,//设置为 true 在点击分页按钮或搜索按钮时，将记住checkbox的选择项
            toolbar: '#toolbar',
            queryParamsType: "",
            queryParams: function (params) {
                params.id = query.id;
                return params;
            },
            onLoadSuccess: function (data) {
                //初始化选项
                $("[name='my-checkbox']").bootstrapSwitch({
                    size: "mini",
                    onColor: "primary",
                    offColor: "danger",
                    onSwitchChange: function (event, state) {
                        var select = $(this);
                        var id = $(this).attr("attrId");
                        $.ajax({
                            type: "post",
                            contentType: "application/json;charset=utf-8",
                            url: "${basePath}/manage/product/attribute/selectImg",
                            data: JSON.stringify({id: id, hasImage: state}),
                            success: function (res) {
                                if (res.code != 1) {
                                    layer.msg(res.message, {icon: 5, time: 2000});
                                }
                                $('#table').bootstrapTable('refresh', {query: query});
                            },
                            fail: function () {
                                layer.msg("修改失败！", {icon: 5});
                            }
                        })
                    }

                });
            },
            columns: [
                {field: 'ck', checkbox: true},
                {field: 'id', title: '编号', sortable: true, align: 'center'},
                {field: 'keyName', title: '属性', align: 'center'},
                {
                    field: 'action',
                    title: '操作',
                    align: 'center',
                    formatter: 'actionFormatter',
                    events: 'actionEvents',
                    clickToSelect: false
                },
                {
                    field: 'isImage',
                    title: '是否有图(单个)',
                    align: 'center',
                    formatter: 'imgFormatter'
                }
            ]
        });

    });
    // 格式化操作按钮
    setPageWidth("500px");
    setPageLength("60%");
    var updateData = {
        title: "'编辑属性'",
        url: "'${basePath}/manage/product/attribute/update/'",
        id: ""
    };
    var deleteData = {
        url: "'${basePath}/manage/product/attribute/delete'",
        id: ""
    };
    // 格式化操作按钮
    function actionFormatter(value, row, index) {
        updateData.id = row.id;
        deleteData.id = row.id;
        var updateHtml = '<a class="update" href="javascript:;" ' +
                'onclick="openPage(' + updateData.title + ',' + updateData.url + ',' + updateData.id + ')" ' +
                'data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>';
        var deleteHtml = '<a class="delete" href="javascript:;"' +
                'onclick="deleteOne(' + deleteData.url + ',' + deleteData.id + ')" ' +
                ' data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>';
        return updateHtml + "  " + deleteHtml;
    }
    function imgFormatter(value, row, index) {
        var hasImage = row.hasImage;
        var id = row.id;
        var switchDiv = '<div class="switch"> ';
        if (hasImage) {
            switchDiv += '<input type="checkbox" name="my-checkbox" checked attrId="' + id + '" /> ';
        } else {
            switchDiv += '<input type="checkbox" name="my-checkbox" attrId="' + id + '"/> ';
        }
        switchDiv += '</div>';
        return switchDiv;
    }
    function initZTree() {
        $.ajax({
            url: "${basePath}/manage/product/category/all",
            type: "GET",
            dataType: "JSON",
            async: false,
            success: function (res) {
                var list = res.data;
                var zNodes = [{id: 0, name: "顶级", open: true}];
                list.forEach(function (data, index, array) {
                    zNodes.push({id: data.id, pId: data.pid, name: data.name});
                });
                $.fn.zTree.init($("#aside_tree"), setting, zNodes);
            }
        });
    }
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick
        }
    };
    function onClick(event, treeId, treeNode, clickFlag) {
        query.id = treeNode.id;
        $('#table').bootstrapTable('refresh', {query: query});
        var treeObj = $.fn.zTree.getZTreeObj("aside_tree");
    }
    initZTree();
</script>
</body>
</html>